package com.bentley.kotlindemo.websocket;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okio.ByteString;

/**
 * @author lee
 * @since 2021/04/02 10:30
 */
public class WsSocketManager {
    private static WsSocketManager instance = null;

    private WsSocketManager() {

    }

    public static WsSocketManager getInstance() {
        if (instance == null)
            synchronized (WsSocketManager.class) {
                if (instance == null) instance = new WsSocketManager();
            }
        return instance;
    }


    private String mWbSocketUrl = null;
    private OkHttpClient mClient = null;
    private WebSocket mWebSocket = null;

    private void initSocket() {
        mWbSocketUrl = "ws://jimu.test/websocket";
        mClient = new OkHttpClient.Builder()
                .pingInterval(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(mWbSocketUrl)
                .build();
        mWebSocket = mClient.newWebSocket(request, new WsListenerkt());
    }

    //发送String消息
    public void send(final String message) {
        if (mWebSocket != null) {
            mWebSocket.send(message);
        }
    }

    //发送byte消息
    public void send(final ByteString message) {
        if (mWebSocket != null) {
            mWebSocket.send(message);
        }
    }

    //主动断开连接
    public void disconnect(int code, String reason) {
        if (mWebSocket != null)
            mWebSocket.close(code, reason);
    }
}

